package cn.com.haopy.yue.ai.wx.service;


import cn.com.haopy.yue.ai.core.component.CacheComponent;
import cn.com.haopy.yue.ai.core.config.tm.TmProperties;
import cn.com.haopy.yue.ai.core.utils.RedisCachePreFix;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSUser;
import cn.com.haopy.yue.ai.db.service.hos.HOSUserService;
import cn.com.haopy.yue.ai.wx.dto.UserInfo;
import cn.com.haopy.yue.ai.wx.dto.UserToken;
import cn.com.haopy.yue.ai.wx.utils.UserTokenManager;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * @author keel
 * @date 2022/4/13
 */
@Service
public class WxHOSUserService {

    @Autowired
    HOSUserService hosUserService;

    @Autowired
    CacheComponent cacheComponent;

    @Resource
    TmProperties tmProperties;


    public Object loginMobile(String mobile) {
        LambdaQueryWrapper<HOSUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(HOSUser::getMobile, mobile);
        List<HOSUser> list = hosUserService.list(queryWrapper);
        if (list.size() > 0) {
            HOSUser busUser = list.get(0);
           /* if (!busUser.getStatus().equals(0)) {
                return ResponseUtil.failMsg("用户已被禁用！");
            }*/

            busUser.setLastLoginTime(LocalDateTime.now());
            if (hosUserService.updateById(busUser)) {
                return loginUser(busUser);
            }


        }
        return ResponseUtil.failMsg("登录失败！");
    }

    public Object wxLogin(UserInfo userInfo, String sessionKey, String openId, String unionId, String ip) {
        LambdaQueryWrapper<HOSUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(HOSUser::getWeixinOpenid, openId);
        List<HOSUser> list = hosUserService.list(queryWrapper);
        if (list.size() > 0) {
            HOSUser busUser = list.get(0);
           /* if (!busUser.getStatus().equals(0)) {
                return ResponseUtil.failMsg("用户已被禁用！");
            }*/

            busUser.setLastLoginTime(LocalDateTime.now());
            busUser.setLastLoginIp(ip);
            busUser.setSessionKey(sessionKey);
            busUser.setWeixinOpenid(openId);
            busUser.setWeixinUnionid(unionId);
            if (!userInfo.getNickName().isEmpty()) {
                busUser.setNickname(userInfo.getNickName());
            }

            if (!userInfo.getAvatarUrl().isEmpty()) {
                busUser.setAvatar(userInfo.getAvatarUrl());
            }


            if (hosUserService.updateById(busUser)) {
                return loginUser(busUser);
            }


        } else {
            HOSUser busUser = new HOSUser();
            busUser.setLastLoginTime(LocalDateTime.now());
            busUser.setCreateTime(LocalDateTime.now());
            busUser.setLastLoginIp(ip);
            busUser.setSessionKey(sessionKey);
            busUser.setWeixinOpenid(openId);
            busUser.setWeixinUnionid(unionId);

            if (!userInfo.getNickName().isEmpty()) {
                busUser.setNickname(userInfo.getNickName());
            }

            if (!userInfo.getAvatarUrl().isEmpty()) {
                busUser.setAvatar(userInfo.getAvatarUrl());
            }
            busUser.setUsername(sessionKey);

            if (hosUserService.save(busUser)) {
                return loginUser(busUser);
            }
        }
        return ResponseUtil.failMsg("登录失败！");
    }


    public Object loginUser(HOSUser busUser) {
        String token = UserTokenManager.generateToken(busUser.getId());
        UserToken loginUserVo = new UserToken();
        loginUserVo.setToken(token);
        loginUserVo.setUserInfo(getUserInfoWidthSign(busUser.getId()));

        cacheComponent.putRaw(RedisCachePreFix.USERTOKEN.getCachePreFix() + busUser.getId(), token, 10 * 24 * 60 * 60);
        cacheComponent.putObj(RedisCachePreFix.USERINFO.getCachePreFix() + token, busUser, 10 * 24 * 60 * 60);

        return ResponseUtil.ok(loginUserVo);
    }


    private UserInfo getUserInfoWidthSign(Integer id) {
        HOSUser user = hosUserService.getById(id);
        if (null != user) {
            UserInfo userVo = new UserInfo();
            userVo.setNickName(user.getNickname());
            userVo.setAvatarUrl(user.getAvatar());
            userVo.setUserId(user.getId());

            userVo.setVipEndDate(user.getVipEndDate());

            return userVo;
        }
        return null;
    }


    public UserInfo getUserInfo(Integer id) {
        if (Objects.nonNull(id)) {
            return getUserInfoWidthSign(id);
        }
        return null;
    }

    /**
     * 设置用户头像和昵称
     *
     * @param userId
     * @param nickName
     * @param avatarUrl
     * @return
     */
    public Object setUserInfo(Integer userId, String nickName, String avatarUrl) {
        HOSUser user = hosUserService.getById(userId);
        if (null != user) {
            user.setAvatar(avatarUrl);
            user.setNickname(nickName);
            if (hosUserService.updateById(user)) {
                return ResponseUtil.ok();
            }
        }
        return ResponseUtil.failMsg("设置失败");
    }


}
